var db      = require('../models');
var _       = require('underscore');
var async   = require('async');

exports.list =  function(req, res){
  console.log("conversation.list", req.body);
  db.Conversation.findAll({where: {user_id :req.user.id}, order: '`started` DESC'}).success(function(conversations) {
    console.log("got conversations", conversations);
    res.json(200, {conversations:conversations});
  });
};

// TODO: Add error handling
exports.top =  function(req, res){
  console.log("conversation.relevant", req.body);

  db.Conversation.findAll({where: {user_id :req.user.id}, order: '`started` DESC', limit:3}).success(function(conversations) {
    console.log("got conversations", conversations);

    async.map(conversations, function(item, callback) {
      db.Note.find({where: {user_id :req.user.id, conversation_id: item.id}, order: '`added` DESC', limit:1}).success(function(note) {
        item.top_note = note;
        callback(null, item)
      });
    }, function(err, results) {
      res.json(200, {conversations:results});
    })

  });
};

exports.create =  function(req, res){
  console.log("conversation.create", req.body);
  var url = decodeURIComponent(req.body.url);
  db.Conversation.create({ 
    user_id: req.user.id, 
    title: req.body.title, 
    started:new Date().toISOString()})
  .success(function(conversation) {

    // If request contains note text, we create an associated Note object
    if (req.body.text) {
      db.Note.create({ 
        user_id:         req.user.id, 
        conversation_id: conversation.id,
        location_id:     req.body.location_id,
        text:            req.body.text,
        added:           new Date()
      })
      .success(function(note) {
        res.send(200, {conversation: conversation, note:note});
      })
      .error(function(err) {
        res.json(400, {message:'Error while creating note'});
      });
    }
  })
  .error(function(err) {
    res.json(400, {message:'Error while creating conversation'});
  });
};

exports.get =  function(req, res){
  console.log("conversation.get", req.query, req.params);
  
  db.Conversation.find(req.params.id).success(function(conversation) {
    if (conversation.user_id == req.user.id) {
      res.json(200, {conversation:conversation});
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};

exports.update =  function(req, res){
  console.log("conversation.update", req.query, req.params, req.body);
  
  db.Conversation.find(req.params.id).success(function(conversation) {
    if (conversation.user_id == req.user.id) {
      conversation.updateAttributes(req.body, _.keys(req.body)).success(function() {
        res.json(200, {conversation:conversation});  
      });
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};

exports.remove =  function(req, res){
    db.Conversation.find(req.params.id).success(function(conversation) {
    if (conversation.user_id == req.user.id) {
      conversation.destroy().success(function() {
        res.json(200, {conversation:conversation});  
      });
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};
